package com.example.zhxy.controller;

import com.example.zhxy.model.Admin;
import com.example.zhxy.model.LoginInfo;
import com.example.zhxy.model.Student;
import com.example.zhxy.model.Teacher;
import com.example.zhxy.service.AdminService;
import com.example.zhxy.service.StudentService;
import com.example.zhxy.service.TeacherService;
import com.example.zhxy.util.CreateVerifiCodeImage;
import com.example.zhxy.util.JwtHelper;
import com.example.zhxy.util.Result;
import com.example.zhxy.util.ResultCodeEnum;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Created with IntelliJ IDEA.
 * ClassName: SystemController
 * Package: com.example.zhxy.controller
 * Description:
 * User: fzykd
 *
 * @Author: LQH
 * Date: 2023-03-13
 * Time: 21:49
 */

@RestController
@RequestMapping("/sms/system")
public class SystemController {

    @Autowired
    private AdminService adminService;

    @Autowired
    private StudentService studentService;

    @Autowired
    private TeacherService teacherService;


    //POST
    //	http://localhost:9001/sms/system/headerImgUpload
    //文件上传  头像图片上传
    @PostMapping("/headerImgUpload")
    public Result headerFile(@RequestParam("multipartFile") MultipartFile multipartFile,
                             HttpServletRequest request){
        //先处理文件名 replace 替换符号 再将所有英文字符转为小写
        String uuid = UUID.randomUUID().toString().replace("-","").toLowerCase();
        //获取文件后缀 getOriginalFilename()获取上传原始的文件名
        String oldFile = multipartFile.getOriginalFilename();
        //找到最后一个点 . 出现的位置
        int i = oldFile.lastIndexOf(".");
        //从最后一个点开始截取 oldFile.substring(i); 拼接uuid
        String newFile = uuid + oldFile.substring(i);

        //保存文件 将文件发送到独立位置上 可以使用concat拼接
        String path = "E:/gitee/binary-TanHua/zhxy/target/classes/static/upload/" + newFile;
        try {
            multipartFile.transferTo(new File(path));
        } catch (IOException e) {
            e.printStackTrace();
        }

        //响应图片路径
        String pathZ = "upload/".concat(newFile);
        return Result.ok(pathZ) ;
    }


    //GET
    //	http://localhost:9001/sms/system/getInfo
    //成功之后跳转
    @GetMapping("/getInfo")
    @ApiOperation("通过token获取用户信息")
    public Result getUserInfoByToken(HttpServletRequest request, @RequestHeader("token")String token){
        boolean expiration = JwtHelper.isExpiration(token);
        if (expiration){
            return Result.build(null,ResultCodeEnum.TOKEN_ERROR);
        }
        //token解析出用户id和类型
        Long userId = JwtHelper.getUserId(token);
        Integer userType = JwtHelper.getUserType(token);

        Map<String,Object> map = new LinkedHashMap<>();
        switch (userType){
            case 1:
                Admin admin = adminService.getAdminById(userId);
                map.put("userType",1);
                map.put("user",admin);
                break;
            case 2:
                Student student = studentService.getStudentById(userId);
                map.put("userType",2);
                map.put("user",student);
                break;
            case 3:
                Teacher teacher = teacherService.getTeacherById(userId);
                map.put("userType",3);
                map.put("user",teacher);
                break;
        }
        //封装的map要返回 前端才知道 返回什么样的页面
        return Result.ok(map);
    }

    //POST
    //	http://localhost:9001/sms/system/login
    //登录验证
    @PostMapping("/login")
    public Result login(@RequestBody LoginInfo loginInfo,
                        HttpServletRequest request){
        //验证码是否有效
        HttpSession session = request.getSession();
        String verifiCode = (String) session.getAttribute("verifiCode");
        String loginVerifiCode = loginInfo.getVerifiCode();
        if ("".equals(verifiCode) || null == verifiCode){
            return Result.fail("验证码失效,请稍后重试!");
        }
        if (!verifiCode.equalsIgnoreCase(loginVerifiCode)){
            return Result.fail("验证码有误,请重新输入!");
        }
        //从Session中移除验证码
        session.removeAttribute("verifiCode");
        //分用户类型

        //准备一个map 用户存放响应的数据
        Map<String,Object> map = new LinkedHashMap<>();
        switch (loginInfo.getUserType()){
            case 1:
                //快捷键 Ctrl + Alt + t
                try {
                    Admin admin = adminService.login(loginInfo);
                    if (null != admin){
                        //用户类型 和 id转成密文 以token形式返回到客户端
                       String token =  JwtHelper.createToken(admin.getId().longValue(),1);
                       map.put("token",token);

                    }else {
                        throw new RuntimeException("用户名或者密码错误!");
                    }
                    return Result.ok(map);
                } catch (RuntimeException e) {
                    e.printStackTrace();

                    return Result.fail().message(e.getMessage());
                }
            case 2:
                try {
                    Student student = studentService.login(loginInfo);
                    if (null != student){
                        //用户类型 和 id转成密文 以token形式返回到客户端
                        String token =  JwtHelper.createToken(student.getId().longValue(),2);
                        map.put("token",token);

                    }else {
                        throw new RuntimeException("用户名或者密码错误!");
                    }
                    return Result.ok(map);
                } catch (RuntimeException e) {
                    e.printStackTrace();

                    return Result.fail().message(e.getMessage());
                }
            case 3:
                try {
                    Teacher teacher = teacherService.login(loginInfo);
                    if (null != teacher){
                        //用户类型 和 id转成密文 以token形式返回到客户端
                        String token =  JwtHelper.createToken(teacher.getId().longValue(),3);
                        map.put("token",token);

                    }else {
                        throw new RuntimeException("用户名或者密码错误!");
                    }
                    return Result.ok(map);
                } catch (RuntimeException e) {
                    e.printStackTrace();

                    return Result.fail().message(e.getMessage());
                }

        }

        return Result.fail().message("查无此用户!");
    }



    //GET
    //http://localhost:9001/sms/system/getVerifiCodeImage?t=1678715322582
    //获取验证码图片
    @GetMapping("/getVerifiCodeImage")
    public void getVerifiCodeImage(HttpServletRequest request,
                                   HttpServletResponse response){
        //获取图片
        BufferedImage verifiCodeImage =  CreateVerifiCodeImage.getVerifiCodeImage();
        //获取图片上的验证码
        String verifiCode = new String(CreateVerifiCodeImage.getVerifiCode());
        //将验证码文本放入到session域 为下一次验证做准备
        HttpSession session = request.getSession();
        session.setAttribute("verifiCode",verifiCode);
        //将验证码图片相应到浏览器
        try {
            ImageIO.write(verifiCodeImage,"JPEG",response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
